import UserModel from "@src/models/User"
import { IBody } from "@src/routes/common/types"
import { resExample } from "./common/responseData"
import { IUser } from "@src/libcommon/modules/user"
import { LoginResponse } from "@src/libcommon/modules/login"
import HttpStatusCodes from "@src/common/HttpStatusCodes"
import { IResponse } from "@src/libcommon"
import { Model } from "sequelize/types"
import md5 from "md5"
import { generateToken } from "@src/util/jwt"

class AuthService {
  /**
   * 用户登录
   * @param {IBody} body
   * @returns {Promise<resExample | LoginResponse>}
   */
  login = async (body: IBody): Promise<IResponse | LoginResponse> => {
    try {
      const { username, password } = body
      const model = await UserModel()
      const user: Model<IUser, IUser> | null = await model.findOne({
        where: {
          username,
          password: md5(password as string),
        }
      })
      if (!user) {
        return resExample({
          code: HttpStatusCodes.BAD_REQUEST,
          message: "用户名或密码错误",
          success: false,
          data: null,
        })
      }
      const token = generateToken({
        id: user.get().id,
        username: user.get().username,
        role: user.get().role,
        email: user.get().email,
      })
      return resExample<LoginResponse>({
        code: HttpStatusCodes.OK,
        message: "登录成功",
        success: true,
        data: {
          token: `Bearer ${token}`,
        }
      })
    } catch (err) {
      throw resExample({
        code: HttpStatusCodes.INTERNAL_SERVER_ERROR,
        message: err.message,
        success: false,
        data: null,
      })
    }
  }

  /**
   * 用户注册
   * @param {IBody} body
   * @returns {Promise<resExample>}
   */
  register = async (body: IBody): Promise<IResponse> => {
    try {
      const { username, password, email } = body
      const model = await UserModel()
      const user: Model<IUser, IUser> | null = await model.findOne({
        where: {
          username,
        },
      })
      if (user) {
        return resExample({
          code: HttpStatusCodes.BAD_REQUEST,
          message: "用户名已存在",
          success: false,
          data: null,
        })
      }

      await model.create({
        username,
        password: md5(password as string),
        email
      })

      return resExample({
        code: HttpStatusCodes.OK,
        message: "注册成功",
        success: true,
        data: null,
      })
    }
    catch (err) {
      if (err.name === "SequelizeUniqueConstraintError") {
        return resExample({
          code: HttpStatusCodes.BAD_REQUEST,
          message: `邮箱 ${body.email} 已被注册`,
          success: false,
          data: null,
        });
      }

      throw resExample({
        code: HttpStatusCodes.INTERNAL_SERVER_ERROR,
        message: err.message,
        success: false,
        data: null,
      })
    }
  }
}

export default new AuthService();
//   /**
//    * 用户登录
//    * @param {IBody} body
//    * @returns {Promise<resExample | LoginResponse>}
//    */
//   login: async (body: IBody): Promise<IResponse | LoginResponse> => {
//     try {
//       const { username, password } = body
//       const model = await UserModel()
//       const user: Model<IUser, IUser> | null = await model.findOne({
//         where: {
//           username,
//           password: md5(password as string),
//         }
//       })
//       if (!user) {
//         return resExample({
//           code: HttpStatusCodes.BAD_REQUEST,
//           message: "用户名或密码错误",
//           success: false,
//           data: null,
//         })
//       }
//       const token = generateToken({
//         id: user.get().id,
//         username: user.get().username,
//         role: user.get().role,
//         email: user.get().email,
//       })
//       return resExample<LoginResponse>({
//         code: HttpStatusCodes.OK,
//         message: "登录成功",
//         success: true,
//         data: {
//           token: `Bearer ${token}`,
//         }
//       })
//     } catch (err) {
//       throw resExample({
//         code: HttpStatusCodes.INTERNAL_SERVER_ERROR,
//         message: err.message,
//         success: false,
//         data: null,
//       })
//     }
//   },

//   /**
//    * 用户注册
//    * @param {IBody} body
//    * @returns {Promise<resExample>}
//    */
//   register: async (body: IBody): Promise<IResponse> => {
//     try {
//       const { username, password, email } = body
//       const model = await UserModel()
//       const user: Model<IUser, IUser> | null = await model.findOne({
//         where: {
//           username,
//         },
//       })
//       if (user) {
//         return resExample({
//           code: HttpStatusCodes.BAD_REQUEST,
//           message: "用户名已存在",
//           success: false,
//           data: null,
//         })
//       }

//       await model.create({
//         username,
//         password: md5(password as string),
//         email
//       })

//       return resExample({
//         code: HttpStatusCodes.OK,
//         message: "注册成功",
//         success: true,
//         data: null,
//       })
//     }
//     catch (err) {
//       if (err.name === "SequelizeUniqueConstraintError") {
//         return resExample({
//           code: HttpStatusCodes.BAD_REQUEST,
//           message: `邮箱 ${body.email} 已被注册`,
//           success: false,
//           data: null,
//         });
//       }

//       throw resExample({
//         code: HttpStatusCodes.INTERNAL_SERVER_ERROR,
//         message: err.message,
//         success: false,
//         data: null,
//       })
//     }
//   }
// }

// export default AuthService